package cn.bincker.mycaptcha.slider.controller;

import cn.bincker.mycaptcha.CaptchaService;
import cn.bincker.mycaptcha.slider.entity.SliderCaptcha;
import cn.bincker.mycaptcha.slider.SliderCaptchaProperties;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.File;

@Controller
@RequestMapping("${my-captcha.slider.path:/my-slider-captcha}")
public class SliderCaptchaController {
    private final SliderCaptchaProperties properties;
    private final CaptchaService<SliderCaptcha> captchaService;

    public SliderCaptchaController(SliderCaptchaProperties properties, CaptchaService<SliderCaptcha> captchaService) {
        this.properties = properties;
        this.captchaService = captchaService;
    }

    @GetMapping
    @ResponseBody
    public SliderCaptcha captcha(HttpServletRequest request){
        return captchaService.getCaptcha(request);
    }

    @GetMapping(value = "{filename:^[\\w-]+\\.\\w+$}", produces = MediaType.IMAGE_PNG_VALUE)
    public ResponseEntity<Resource> getCaptcha(@PathVariable String filename){
        var cacheConfig = properties.getCache();
        var file = new File(cacheConfig.getCaptchaPath(), filename);
        if(!file.exists()) return ResponseEntity.notFound().build();
        return ResponseEntity.ok(new FileSystemResource(file));
    }
}
